const fs = require('fs');
const path = require('path');

function removeLastPipe(input: string): string {
  // 使用正则表达式找到最后一个 ' | ' 分隔符
  const lastPipeIndex = input.lastIndexOf(' | ');
  // 确保存在最后一个 ' | ' 分隔符
  if (lastPipeIndex !== -1) {
    // 删除最后一个 ' | ' 分隔符
    return input.slice(0, lastPipeIndex);
  } else {
    // 如果不存在最后一个 ' | ' 分隔符，返回原始字符串
    return input;
  }
}

function toPascalCase(str: string): string {
  // 分割字符串，根据'/'或者'-'或者'_'进行分割
  const parts = str.split(/[\s_/-]+/);
  // 将每个部分的首字母大写，然后拼接起来
  const pascalCased = parts.map(part => {
    return part.charAt(0).toUpperCase() + part.slice(1);
  }).join('');
  return pascalCased;
}

const pagesJsonPlugin = {
	name: 'kux-pages-json',
	// apply: 'build',
	config(config) {
		// const pagesJsonResolvedPath = await this.resolve('/pages.json');
		// 读取pages.json
		const pagesJsonPath = path.resolve(config.root, './', 'pages.json');
		const pagesJsonContent = fs.readFileSync(pagesJsonPath, 'utf-8');
		// 移除pages.json中的注释
		const jsonWithoutComments = pagesJsonContent.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '');
		const timestamp : number = Date.now();
		const date : Date = new Date(timestamp);
		function formatTime(date : Date) : string {
			const year : number = date.getFullYear();
			const month : number = date.getMonth() + 1; // 月份是从0开始的
			const day : number = date.getDate();
			const hours : number = date.getHours();
			const minutes : number = date.getMinutes();
			const seconds : number = date.getSeconds();

			// 格式化数字，确保它们前面有前导零
			const formattedMonth : string = month < 10 ? `0${month}` : month.toString();
			const formattedDay : string = day < 10 ? `0${day}` : day.toString();
			const formattedHours : string = hours < 10 ? `0${hours}` : hours.toString();
			const formattedMinutes : string = minutes < 10 ? `0${minutes}` : minutes.toString();
			const formattedSeconds : string = seconds < 10 ? `0${seconds}` : seconds.toString();

			// 组合成你想要的格式
			return `${year}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
		}

		try {
			const version = 'v1.0.2';
			const pagesJson = JSON.parse(jsonWithoutComments);

			let routerContent = `/**\n`;
			routerContent += `* pages.json映射文件，该文件每次重新编译时都会由插件自动生成，不要直接在该文件内编辑！！！\n`;
			routerContent += `* @author kviewui <kviewui@163.com>\n`;
			routerContent += `* @created ${formatTime(date)}\n`;
			routerContent += `* @version ${version}\n`;
			routerContent += `* @copyright Copyright (c) ${date.getFullYear()} The Authors.\n`;
			routerContent += `* @license MIT License\n`;
			routerContent += `* Permission is hereby granted, free of charge, to any person obtaining a copy\n`;
			routerContent += `* of this software and associated documentation files (the "Software"), to deal\n`;
			routerContent += `* in the Software without restriction, including without limitation the rights\n`;
			routerContent += `* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n`;
			routerContent += `* copies of the Software, and to permit persons to whom the Software is\n`;
			routerContent += `* furnished to do so, subject to the following conditions:\n\n`;
			routerContent += `* The above copyright notice and this permission notice shall be included in all\n`;
			routerContent += `* copies or substantial portions of the Software.\n\n`;
			routerContent += `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n`;
			routerContent += `* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n`;
			routerContent += `* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n`;
			routerContent += `* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n`;
			routerContent += `* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n`;
			routerContent += `* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n`;
			routerContent += `* SOFTWARE.\n`;
			routerContent += `*/\n\n`;
			// 遍历 pages.json 生成PagePath
			let Path = '';
			let Name = '';
			let Meta = {};
			pagesJson.pages.map(page => {
				Path += `'/${page.path}' | `;
				Name += `'${page.name ?? toPascalCase(page.path)}' | `;
			});
			routerContent += `export type PagePath = ${removeLastPipe(Path)};\n\n`;
			routerContent += `export type PageName = ${removeLastPipe(Name)};\n\n`;
			routerContent += `export type PageItem = {\n`;
			routerContent += `\tpath: PagePath\n`;
			routerContent += `\tname?: string\n`;
			routerContent += `\tmeta?: UTSJSONObject\n`;
			routerContent += `\tquery?: UTSJSONObject\n`;
			routerContent += `\tdata?: UTSJSONObject\n`;
			routerContent += `};\n\n`;
			// routerContent += `import { RouteRecordNormalized } from './common/interface.uts';\n\n`;
			routerContent += `export const pages: PageItem[] = [\n`;
			// 遍历 pages.json 中的 pages 数组
			pagesJson.pages.map(page => {
				routerContent += `\t{\n`;
				routerContent += `\t\tpath: '/${page.path}',\n`;
				routerContent += `\t\tname: '${page.name ?? toPascalCase(page.path)}',\n`;
				// routerContent += `\t\tmeta: ${page.meta ?? {}},\n`;
				// routerContent += `\t\tquery: ${page.query ?? {}},\n`;
				// routerContent += `\t\tdata: ${page.data ?? {}},\n`;
				routerContent += `\t},\n`;
				Path += `'/${page.path}' | `;
			});
			routerContent += `];\n\n`;

			// 写入到router配置文件
			// const outputResolvedPath = await this.resolve('/pageJsonRouter.ts');
			const outputPath = path.resolve(config.root, './', 'pagesJsonRouter.uts');
			// 检查文件是否可写，如果不可写，尝试修改权限
			fs.access(outputPath, fs.constants.F_OK | fs.constants.W_OK, (err) => {
				if (err) {
					if (err.code === 'ENOENT') {
						// 文件不存在，直接写入
						fs.writeFileSync(outputPath, routerContent);
						console.info('router write complete');
					} else if (err.code === 'EACCES') {
						// 没有写入权限，尝试修改文件权限
						fs.chmod(outputPath, 0o666, (chmodErr) => {
							if (chmodErr) {
								throw chmodErr;
							}
							// 修改权限后再次尝试写入
							fs.writeFileSync(outputPath, routerContent);
							console.info('router write complete');
						});
					} else {
						throw err;
					}
				} else {
					// 文件可写，直接写入
					fs.writeFileSync(outputPath, routerContent);
					console.info('router write complete');
				}
			})
		} catch (parseErr) {
			console.error('Error parsing JSON:', parseErr);
			throw parseErr;
		}
	}
};

module.exports = pagesJsonPlugin;